<template>
  <!-- First Level -->
  <div class="first-level-wrap">
    <condition
      ref="condition"
      :props="firstLevel"
      @handleChange="handleFirstLevel"
    ></condition>
    <div class="first-level-from-box">
      <!-- User Attribute Line -->
      <el-card class="attribute-card" ref="attribute">
        <div slot="header" class="clearfix">
          <span>用户属性</span>
          <el-dropdown @command="handleAddAttrs" style="float: right;">
            <el-button type="success" :disabled="is_preview">
              添加<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="a">条件</el-dropdown-item>
              <el-dropdown-item command="b">条件组</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>

        <div class="second-level-wrap">
          <!-- Second Level -->
          <condition
            v-if="attrList.length + attrCard.length > 1"
            :props="secondAttrLevel"
            @handleChange="handleSecondAttrLevel"
          ></condition>

          <div class="second-level-form-box" ref="secondAttribute">
            <div v-for="(item, index) in attrList" :key="item.index">
              <el-form
                :inline="true"
                :model="item"
                :ref="'attrValidateForm' + index"
              >
                <el-form-item
                  prop="attr"
                  :rules="{
                    required: true,
                    message: '请选择',
                    trigger: 'change'
                  }"
                >
                  <el-select
                    v-model="item.attr"
                    @change="handleAttrRuleChange(item, index)"
                    placeholder="请选择用户属性"
                    :disabled="is_preview"
                    filterable
                    clearable
                  >
                    <el-option
                      v-for="(prop, i) in userAttrs"
                      :key="i"
                      :label="prop.indexName"
                      :value="prop.indexCode"
                    ></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item
                  prop="rule"
                  :rules="{
                    required: true,
                    message: '请选择',
                    trigger: 'change'
                  }"
                >
                  <el-select
                    v-model="item.rule"
                    placeholder="请选择匹配规则"
                    :disabled="is_preview"
                    filterable
                    @change="attributeRule(item)"
                    clearable
                  >
                    <el-option
                      v-for="(prop, i) in item.ruleList"
                      :key="i"
                      :label="prop.label"
                      :value="prop.value"
                    ></el-option>
                  </el-select>
                </el-form-item>

                <template v-if="item.element === 'Select'">
                  <el-form-item
                    v-show="
                      !item.rule ||
                        item.rule == 'include' ||
                        item.rule == 'uninclude'
                    "
                    :prop="
                      item.rule == 'empty' || item.rule == 'unempty'
                        ? ''
                        : 'attrVal'
                    "
                    :rules="{
                      required: true,
                      message: '请选择',
                      trigger: 'change'
                    }"
                  >
                    <el-select
                      v-if="
                        !item.rule ||
                          item.rule == 'include' ||
                          item.rule == 'uninclude'
                      "
                      :ref="'attributeConditionsSelect' + index"
                      v-model="item.attrVal"
                      :disabled="is_preview"
                      multiple
                      filterable
                      clearable
                    >
                      <el-option
                        v-for="(prop, i) in item.valList"
                        :key="i"
                        :label="prop"
                        :value="prop"
                      ></el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item
                    v-show="item.rule == 'equal' || item.rule == 'unequal'"
                    :prop="
                      item.rule == 'empty' || item.rule == 'unempty'
                        ? ''
                        : 'attrVal'
                    "
                    :rules="{
                      required: true,
                      message: '请选择',
                      trigger: 'change'
                    }"
                  >
                    <el-select
                      v-if="item.rule == 'equal' || item.rule == 'unequal'"
                      :ref="'attributeConditionsSelect' + index"
                      v-model="item.attrVal"
                      :disabled="is_preview"
                      filterable
                      clearable
                    >
                      <el-option
                        v-for="(prop, i) in item.valList"
                        :key="i"
                        :label="prop"
                        :value="prop"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </template>

                <template v-if="item.element === 'Date'">
                  <el-form-item
                    v-show="item.element === 'Date'"
                    :prop="
                      item.rule == 'empty' || item.rule == 'unempty'
                        ? ''
                        : 'attrVal'
                    "
                    :rules="{
                      required: true,
                      message: '请选择',
                      trigger: 'change'
                    }"
                  >
                    <el-date-picker
                      v-if="item.rule !== 'section'"
                      v-model="item.attrVal"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="选择日期"
                      :disabled="is_preview"
                      clearable
                    ></el-date-picker>
                    <el-date-picker
                      v-if="item.rule == 'section'"
                      v-model="item.attrVal"
                      type="daterange"
                      :disabled="is_preview"
                      value-format="yyyy-MM-dd"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                    >
                    </el-date-picker>
                  </el-form-item>
                </template>

                <template v-if="item.element === 'Number'">
                  <el-form-item
                    v-show="item.element === 'Number'"
                    :prop="
                      item.rule == 'empty' || item.rule == 'unempty'
                        ? ''
                        : 'attrVal'
                    "
                    :rules="{
                      required: true,
                      message: '请输入',
                      trigger: 'blur'
                    }"
                  >
                    <el-input
                      v-model="item.attrVal"
                      type="Number"
                      placeholder="输入内容"
                      :disabled="is_preview"
                      clearable
                    ></el-input>
                  </el-form-item>
                </template>

                <template v-if="item.element === 'Text'">
                  <el-form-item
                    v-show="item.element === 'Text'"
                    :prop="
                      item.rule == 'empty' || item.rule == 'unempty'
                        ? ''
                        : 'attrVal'
                    "
                    :rules="{
                      required: true,
                      message: '请输入',
                      trigger: 'blur'
                    }"
                  >
                    <el-input
                      v-model="item.attrVal"
                      placeholder="输入内容"
                      :disabled="is_preview"
                      clearable
                    ></el-input>
                  </el-form-item>
                </template>

                <el-form-item>
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    @click="handleDelAttr(index)"
                    circle
                    :disabled="is_preview"
                  ></el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- Third Attribute Level -->
            <el-card
              v-for="item in attrCard"
              :key="item.index + '-only'"
              class="attribute-child-card"
            >
              <div slot="header" class="clearfix">
                <el-button
                  type="success"
                  @click="handleAddThirdAttribute(item)"
                  :disabled="is_preview"
                  style="float: right;"
                  >添加</el-button
                >
              </div>

              <div class="third-level-wrap">
                <condition
                  v-if="item.child.length > 1"
                  :props="item.condition"
                  @handleChange="handleThirdAttributeLevel($event, item)"
                ></condition>

                <div
                  class="third-level-form-box"
                  :ref="'thirdAttribute' + item.index"
                >
                  <div v-for="(item1, index) in item.child" :key="item1.index">
                    <el-form
                      :inline="true"
                      :model="item1"
                      :ref="'attrValidateForm' + item.index + index"
                    >
                      <el-form-item
                        prop="attr"
                        :rules="{
                          required: true,
                          message: '请选择',
                          trigger: 'change'
                        }"
                      >
                        <el-select
                          v-model="item1.attr"
                          @change="
                            handleThirdAttrRuleChange(item, item1, index)
                          "
                          placeholder="请选择用户属性"
                          :disabled="is_preview"
                          filterable
                          clearable
                        >
                          <el-option
                            v-for="(prop, i) in userAttrs"
                            :key="i"
                            :label="prop.indexName"
                            :value="prop.indexCode"
                          ></el-option>
                        </el-select>
                      </el-form-item>

                      <el-form-item
                        prop="rule"
                        :rules="{
                          required: true,
                          message: '请选择',
                          trigger: 'change'
                        }"
                      >
                        <el-select
                          v-model="item1.rule"
                          placeholder="请选择匹配规则"
                          :disabled="is_preview"
                          filterable
                          @change="attributeRule(item1)"
                          clearable
                        >
                          <el-option
                            v-for="(prop, i) in item1.ruleList"
                            :key="i"
                            :label="prop.label"
                            :value="prop.value"
                          ></el-option>
                        </el-select>
                      </el-form-item>

                      <template v-if="item1.element === 'Select'">
                        <el-form-item
                          v-show="
                            !item1.rule ||
                              item1.rule == 'include' ||
                              item1.rule == 'uninclude'
                          "
                          :prop="
                            item1.rule == 'empty' || item1.rule == 'unempty'
                              ? ''
                              : 'attrVal'
                          "
                          :rules="{
                            required: true,
                            message: '请选择',
                            trigger: 'change'
                          }"
                        >
                          <el-select
                            v-if="
                              !item1.rule ||
                                item1.rule == 'include' ||
                                item1.rule == 'uninclude'
                            "
                            :ref="'attributeConditionsSelect' + index"
                            v-model="item1.attrVal"
                            :disabled="is_preview"
                            multiple
                            filterable
                            clearable
                          >
                            <el-option
                              v-for="(prop, i) in item1.valList"
                              :key="i"
                              :label="prop"
                              :value="prop"
                            ></el-option>
                          </el-select>
                        </el-form-item>

                        <el-form-item
                          v-show="
                            item1.rule == 'equal' || item1.rule == 'unequal'
                          "
                          :prop="
                            item1.rule == 'empty' || item1.rule == 'unempty'
                              ? ''
                              : 'attrVal'
                          "
                          :rules="{
                            required: true,
                            message: '请选择',
                            trigger: 'change'
                          }"
                        >
                          <el-select
                            v-if="
                              item1.rule == 'equal' || item1.rule == 'unequal'
                            "
                            :ref="'attributeConditionsSelect' + index"
                            v-model="item1.attrVal"
                            :disabled="is_preview"
                            filterable
                            clearable
                          >
                            <el-option
                              v-for="(prop, i) in item1.valList"
                              :key="i"
                              :label="prop"
                              :value="prop"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </template>

                      <template v-if="item1.element === 'Date'">
                        <el-form-item
                          v-show="item1.element === 'Date'"
                          :prop="
                            item1.rule == 'empty' || item1.rule == 'unempty'
                              ? ''
                              : 'attrVal'
                          "
                          :rules="{
                            required: true,
                            message: '请选择',
                            trigger: 'change'
                          }"
                        >
                          <el-date-picker
                            v-if="item1.rule !== 'section'"
                            v-model="item1.attrVal"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="选择日期"
                            :disabled="is_preview"
                            clearable
                          ></el-date-picker>
                          <el-date-picker
                            v-if="item1.rule === 'section'"
                            v-model="item1.attrVal"
                            type="daterange"
                            value-format="yyyy-MM-dd"
                            :disabled="is_preview"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                          >
                          </el-date-picker>
                        </el-form-item>
                      </template>

                      <template v-if="item1.element === 'Number'">
                        <el-form-item
                          v-show="item1.element === 'Number'"
                          :prop="
                            item1.rule == 'empty' || item1.rule == 'unempty'
                              ? ''
                              : 'attrVal'
                          "
                          :rules="{
                            required: true,
                            message: '请输入',
                            trigger: 'blur'
                          }"
                        >
                          <el-input
                            v-model="item1.attrVal"
                            type="Number"
                            placeholder="输入内容"
                            :disabled="is_preview"
                            clearable
                          ></el-input>
                        </el-form-item>
                      </template>

                      <template v-if="item1.element === 'Text'">
                        <el-form-item
                          v-show="item1.element === 'Text'"
                          :prop="
                            item1.rule == 'empty' || item1.rule == 'unempty'
                              ? ''
                              : 'attrVal'
                          "
                          :rules="{
                            required: true,
                            message: '请输入',
                            trigger: 'blur'
                          }"
                        >
                          <el-input
                            v-model="item1.attrVal"
                            placeholder="输入内容"
                            :disabled="is_preview"
                            clearable
                          ></el-input>
                        </el-form-item>
                      </template>

                      <el-form-item>
                        <el-button
                          type="danger"
                          icon="el-icon-delete"
                          @click="handleDelThirdAttr(item, index)"
                          circle
                          :disabled="is_preview"
                        ></el-button>
                      </el-form-item>
                    </el-form>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </el-card>

      <!-- divider Line -->
      <el-divider style="margin-left:30px;"></el-divider>

      <!-- User Action Line -->
      <el-card class="action-card" ref="behavior">
        <div slot="header" class="clearfix">
          <span>用户行为</span>
          <el-dropdown @command="handleAddBehavior" style="float: right;">
            <el-button type="success" :disabled="is_preview">
              添加<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="a">条件</el-dropdown-item>
              <el-dropdown-item command="b">条件组</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>

        <div class="second-level-wrap">
          <!-- Second Behavior Level -->
          <condition
            v-if="behaviorCard.length + behaviorList.length > 1"
            :props="secondBehaviorLevel"
            @handleChange="handleSecondBehaviorLevel"
          ></condition>

          <div class="second-level-form-box" ref="secondBehavior">
            <div v-for="(item, index) in behaviorList" :key="item.index">
              <el-form
                :inline="true"
                :model="item"
                :ref="'behaviorValidateForm' + index"
              >
                <el-form-item
                  prop="behavior"
                  :rules="{
                    required: true,
                    message: '请选择',
                    trigger: 'change'
                  }"
                >
                  <el-select
                    v-model="item.behavior"
                    @change="handleBehaviorRuleChange(item, index)"
                    placeholder="请选择用户行为"
                    :disabled="is_preview"
                    filterable
                    clearable
                  >
                    <el-option
                      v-for="(prop, i) in userBehaviors"
                      :key="i"
                      :label="prop.indexName"
                      :value="prop.indexCode"
                    ></el-option>
                  </el-select>
                </el-form-item>

                <template v-if="item.isPeriod === '1'">
                  <el-form-item
                    prop="timeRange"
                    :rules="{
                      required: true,
                      message: '请选择',
                      trigger: 'change'
                    }"
                    style="width: 200px;"
                  >
                    <el-select
                      v-model="item.timeRange"
                      @change="handleTimeRangeChange(index, item)"
                      placeholder="请选择时间范围"
                      :disabled="is_preview"
                      clearable
                      filterable
                    >
                      <el-option
                        v-for="(prop, i) in dateRange"
                        :key="i"
                        :label="prop.label"
                        :value="prop.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </template>

                <el-form-item
                  v-if="item.dimensionList.length > 1 || !item.behavior"
                  prop="dimension"
                  :rules="{ message: '请选择', trigger: 'change' }"
                  style="width: 160px;"
                >
                  <el-select
                    v-if="item.dimensionList.length > 1 || !item.behavior"
                    v-model="item.dimension"
                    placeholder="请选择统计维度"
                    :disabled="is_preview"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="(prop, i) in item.dimensionList"
                      :key="i"
                      :label="prop.label"
                      :value="prop.value"
                    ></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item
                  prop="rule"
                  :rules="{
                    required: true,
                    message: '请选择',
                    trigger: 'change'
                  }"
                  style="width: 160px;"
                >
                  <el-select
                    v-model="item.rule"
                    placeholder="请选择匹配规则"
                    :disabled="is_preview"
                    @change="handleBehaviorRuleSection(index, item)"
                    filterable
                    clearable
                  >
                    <el-option
                      v-for="(prop, i) in item.ruleList"
                      :key="i"
                      :label="prop.label"
                      :value="prop.value"
                    ></el-option>
                  </el-select>
                </el-form-item>

                <template v-if="item.element === 'Select'">
                  <el-form-item
                    v-show="
                      !item.rule ||
                        ((item.rule === 'include' ||
                          item.rule === 'uninclude') &&
                          (item.behavior === 'sys_source_zh' ||
                            item.behavior === 'sys_source_last'))
                    "
                    :prop="
                      item.rule == 'empty' || item.rule == 'unempty'
                        ? ''
                        : 'actionNum'
                    "
                    :rules="{
                      required: true,
                      message: '请选择',
                      trigger: 'blur'
                    }"
                  >
                    <el-select
                      v-if="
                        !item.rule ||
                          ((item.rule === 'include' ||
                            item.rule === 'uninclude') &&
                            (item.behavior === 'sys_source_zh' ||
                              item.behavior === 'sys_source_last'))
                      "
                      v-model="item.actionNum"
                      :disabled="is_preview"
                      multiple
                      filterable
                      clearable
                    >
                      <el-option
                        v-for="(prop, i) in item.valList"
                        :key="i"
                        :label="prop"
                        :value="prop"
                      ></el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item
                    v-show="
                      item.rule &&
                        (item.rule === 'equal' || item.rule === 'unequal') &&
                        (item.behavior === 'sys_source_zh' ||
                          item.behavior === 'sys_source_last')
                    "
                    :prop="
                      item.rule == 'empty' || item.rule == 'unempty'
                        ? ''
                        : 'actionNum'
                    "
                    :rules="{
                      required: true,
                      message: '请选择',
                      trigger: 'blur'
                    }"
                  >
                    <el-select
                      v-if="
                        item.rule &&
                          (item.rule === 'equal' || item.rule === 'unequal') &&
                          (item.behavior === 'sys_source_zh' ||
                            item.behavior === 'sys_source_last')
                      "
                      v-model="item.actionNum"
                      :disabled="is_preview"
                      filterable
                      clearable
                    >
                      <el-option
                        v-for="(prop, i) in item.valList"
                        :key="i"
                        :label="prop"
                        :value="prop"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </template>

                <template v-if="item.element === 'Date'" style="width: 200px;">
                  <el-form-item
                    v-if="item.element === 'Date'"
                    :prop="
                      item.rule == 'empty' || item.rule == 'unempty'
                        ? ''
                        : 'actionNum'
                    "
                    :rules="{
                      required: true,
                      message: '请选择',
                      trigger: 'change'
                    }"
                  >
                    <el-date-picker
                      v-if="!item.section"
                      v-model="item.actionNum"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="选择日期"
                      :disabled="is_preview"
                      clearable
                    ></el-date-picker>

                    <el-date-picker
                      v-if="item.section"
                      v-model="item.actionNum"
                      type="daterange"
                      value-format="yyyy-MM-dd"
                      :disabled="is_preview"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                    >
                    </el-date-picker>
                  </el-form-item>
                </template>

                <template v-if="item.element === 'Number'">
                  <el-form-item
                    :prop="
                      item.rule == 'empty' || item.rule == 'unempty'
                        ? ''
                        : 'actionNum'
                    "
                    :rules="{
                      required: true,
                      message: '请输入',
                      trigger: 'blur'
                    }"
                  >
                    <el-input
                      v-model="item.actionNum"
                      type="Number"
                      placeholder="输入数字"
                      :disabled="is_preview"
                      style="width: 110px;"
                      clearable
                    ></el-input>
                  </el-form-item>

                  <template v-if="item.section">
                    <el-form-item>至</el-form-item>

                    <el-form-item
                      prop="actionEndNum"
                      :rules="{
                        required: true,
                        message: '请输入',
                        trigger: 'blur'
                      }"
                    >
                      <el-input
                        v-model="item.actionEndNum"
                        type="Number"
                        placeholder="输入数字"
                        :disabled="is_preview"
                        style="width: 110px;"
                        clearable
                      ></el-input>
                    </el-form-item>
                  </template>
                </template>

                <template v-if="item.element === 'Text'">
                  <el-form-item
                    :prop="
                      item.rule == 'empty' || item.rule == 'unempty'
                        ? ''
                        : 'actionNum'
                    "
                    :rules="{
                      required: true,
                      message: '请输入',
                      trigger: 'blur'
                    }"
                  >
                    <el-input
                      v-model="item.actionNum"
                      placeholder="输入内容"
                      :disabled="is_preview"
                      clearable
                    ></el-input>
                  </el-form-item>
                </template>

                <el-form-item>
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    @click="handleDelBehavior(index)"
                    circle
                    :disabled="is_preview"
                  ></el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- Third Behavior Level -->
            <el-card
              v-for="item in behaviorCard"
              :key="item.index + '-only'"
              class="action-child-card"
            >
              <div slot="header" class="clearfix">
                <el-button
                  type="success"
                  @click="handleAddThirdBehavior(item)"
                  :disabled="is_preview"
                  style="float: right;"
                  >添加</el-button
                >
              </div>

              <div class="third-level-wrap">
                <condition
                  v-if="item.child.length > 1"
                  :props="item.condition"
                  @handleChange="handleThirdBehaviorLevel($event, item)"
                ></condition>

                <div
                  class="third-level-form-box"
                  :ref="'thirdBehavior' + item.index"
                >
                  <div v-for="(item1, index) in item.child" :key="item1.index">
                    <el-form
                      :inline="true"
                      :model="item1"
                      :ref="'behaviorValidateForm' + item.index + index"
                    >
                      <el-form-item
                        prop="behavior"
                        :rules="{
                          required: true,
                          message: '请选择',
                          trigger: 'change'
                        }"
                      >
                        <el-select
                          v-model="item1.behavior"
                          @change="
                            handleThirdBehaviorRuleChange(item, item1, index)
                          "
                          placeholder="请选择用户行为"
                          :disabled="is_preview"
                          filterable
                          clearable
                        >
                          <el-option
                            v-for="(prop, i) in userBehaviors"
                            :key="i"
                            :label="prop.indexName"
                            :value="prop.indexCode"
                          ></el-option>
                        </el-select>
                      </el-form-item>

                      <template v-if="item1.isPeriod === '1'">
                        <el-form-item
                          prop="timeRange"
                          :rules="{
                            required: true,
                            message: '请选择',
                            trigger: 'change'
                          }"
                          style="width: 200px;"
                        >
                          <el-select
                            v-model="item1.timeRange"
                            @change="
                              handleThirdTimeRangeChange(item, item1, index)
                            "
                            placeholder="请选择时间范围"
                            :disabled="is_preview"
                            clearable
                            filterable
                          >
                            <el-option
                              v-for="(prop, i) in dateRange"
                              :key="i"
                              :label="prop.label"
                              :value="prop.value"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </template>

                      <el-form-item
                        v-if="item1.dimensionList.length > 1 || !item1.behavior"
                        prop="dimension"
                        :rules="{ message: '请输入', trigger: 'change' }"
                        style="width: 160px;"
                      >
                        <el-select
                          v-if="
                            item1.dimensionList.length > 1 || !item1.behavior
                          "
                          v-model="item1.dimension"
                          placeholder="请选择统计维度"
                          :disabled="is_preview"
                          clearable
                          filterable
                        >
                          <el-option
                            v-for="(prop, i) in item1.dimensionList"
                            :key="i"
                            :label="prop.label"
                            :value="prop.value"
                          ></el-option>
                        </el-select>
                      </el-form-item>

                      <el-form-item
                        prop="rule"
                        :rules="{
                          required: true,
                          message: '请选择',
                          trigger: 'change'
                        }"
                        style="width: 160px;"
                      >
                        <el-select
                          v-model="item1.rule"
                          placeholder="请选择匹配规则"
                          :disabled="is_preview"
                          @change="
                            handleThirdBehaviorRuleSection(item, item1, index)
                          "
                          filterable
                          clearable
                        >
                          <el-option
                            v-for="(prop, i) in item1.ruleList"
                            :key="i"
                            :label="prop.label"
                            :value="prop.value"
                          ></el-option>
                        </el-select>
                      </el-form-item>

                      <template v-if="item1.element === 'Select'">
                        <el-form-item
                          v-show="
                            !item1.rule ||
                              ((item1.rule === 'include' ||
                                item1.rule === 'uninclude') &&
                                (item1.behavior === 'sys_source_zh' ||
                                  item1.behavior === 'sys_source_last'))
                          "
                          :prop="
                            item1.rule == 'empty' || item1.rule == 'unempty'
                              ? ''
                              : 'actionNum'
                          "
                          :rules="{
                            required: true,
                            message: '请选择',
                            trigger: 'blur'
                          }"
                        >
                          <el-select
                            v-if="
                              !item1.rule ||
                                ((item1.rule === 'include' ||
                                  item1.rule === 'uninclude') &&
                                  (item1.behavior === 'sys_source_zh' ||
                                    item1.behavior === 'sys_source_last'))
                            "
                            v-model="item1.actionNum"
                            :disabled="is_preview"
                            multiple
                            filterable
                            clearable
                          >
                            <el-option
                              v-for="(prop, i) in item1.valList"
                              :key="i"
                              :label="prop"
                              :value="prop"
                            ></el-option>
                          </el-select>
                        </el-form-item>

                        <el-form-item
                          v-show="
                            item1.rule &&
                              (item1.rule === 'equal' ||
                                item1.rule === 'unequal') &&
                              (item1.behavior === 'sys_source_zh' ||
                                item1.behavior === 'sys_source_last')
                          "
                          :prop="
                            item1.rule == 'empty' || item1.rule == 'unempty'
                              ? ''
                              : 'actionNum'
                          "
                          :rules="{
                            required: true,
                            message: '请选择',
                            trigger: 'blur'
                          }"
                        >
                          <el-select
                            v-if="
                              item1.rule &&
                                (item1.rule === 'equal' ||
                                  item1.rule === 'unequal') &&
                                (item1.behavior === 'sys_source_zh' ||
                                  item1.behavior === 'sys_source_last')
                            "
                            v-model="item1.actionNum"
                            :disabled="is_preview"
                            filterable
                            clearable
                          >
                            <el-option
                              v-for="(prop, i) in item1.valList"
                              :key="i"
                              :label="prop"
                              :value="prop"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </template>

                      <template v-if="item1.element === 'Date'">
                        <el-form-item
                          :prop="
                            item1.rule == 'empty' || item1.rule == 'unempty'
                              ? ''
                              : 'actionNum'
                          "
                          :rules="{
                            required: true,
                            message: '请选择',
                            trigger: 'change'
                          }"
                        >
                          <el-date-picker
                            v-if="!item1.section"
                            v-model="item1.actionNum"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="选择日期"
                            :disabled="is_preview"
                            clearable
                          ></el-date-picker>
                          <el-date-picker
                            v-if="item1.section"
                            v-model="item1.actionNum"
                            type="daterange"
                            value-format="yyyy-MM-dd"
                            :disabled="is_preview"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                          >
                          </el-date-picker>
                        </el-form-item>
                      </template>

                      <template v-if="item1.element === 'Number'">
                        <el-form-item
                          :prop="
                            item1.rule == 'empty' || item1.rule == 'unempty'
                              ? ''
                              : 'actionNum'
                          "
                          :rules="{
                            required: true,
                            message: '请输入',
                            trigger: 'blur'
                          }"
                        >
                          <el-input
                            v-model="item1.actionNum"
                            type="Number"
                            placeholder="输入数字"
                            :disabled="is_preview"
                            style="width: 110px;"
                            clearable
                          ></el-input>
                        </el-form-item>

                        <template v-if="item1.section">
                          <el-form-item>至</el-form-item>

                          <el-form-item
                            prop="actionEndNum"
                            :rules="{
                              required: true,
                              message: '请输入',
                              trigger: 'blur'
                            }"
                          >
                            <el-input
                              v-model="item1.actionEndNum"
                              type="Number"
                              placeholder="输入数字"
                              :disabled="is_preview"
                              style="width: 110px;"
                              clearable
                            ></el-input>
                          </el-form-item>
                        </template>
                      </template>

                      <template v-if="item1.element === 'Text'">
                        <el-form-item
                          :prop="
                            item1.rule == 'empty' || item1.rule == 'unempty'
                              ? ''
                              : 'actionNum'
                          "
                          :rules="{
                            required: true,
                            message: '请输入',
                            trigger: 'blur'
                          }"
                        >
                          <el-input
                            v-model="item1.actionNum"
                            placeholder="输入内容"
                            :disabled="is_preview"
                            clearable
                          ></el-input>
                        </el-form-item>
                      </template>

                      <el-form-item>
                        <el-button
                          type="danger"
                          icon="el-icon-delete"
                          @click="handleDelThirdBehavior(item, index)"
                          circle
                          :disabled="is_preview"
                        ></el-button>
                      </el-form-item>
                    </el-form>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </el-card>
    </div>

    <!-- date range -->
    <el-dialog
      title="时间设置"
      v-if="dateDialog.visible"
      :visible.sync="dateDialog.visible"
      @closed="handleDateDialogClose"
      width="30%"
      custom-class="custom-dialog"
    >
      <div class="dialog-body">
        <el-form
          ref="dateForm"
          :model="dateRangeForm"
          :rules="dateRangeRules"
          label-width="80px"
        >
          <el-form-item
            label="日期范围"
            prop="staticDate"
            v-if="dateRangeForm.type === 'static_time'"
          >
            <el-date-picker
              v-model="dateRangeForm.staticDate"
              type="daterange"
              value-format="yyyy-MM-dd"
              :disabled="is_preview"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>

          <el-form-item
            label="开始时间"
            prop="dynamicDate"
            v-if="dateRangeForm.type === 'dynamic_time'"
          >
            <el-date-picker
              v-model="dateRangeForm.dynamicDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item
            label="过去N天"
            prop="pastDays"
            v-if="dateRangeForm.type === 'dynamic_time'"
            style="width:300px;"
          >
            <el-input
              v-model="dateRangeForm.pastDays"
              placeholder="请输入天数"
              @blur="reservedInteger"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <div class="tips">提示：数仓从2021年1月1号开始提供数据</div>
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="success" @click="handleDateFormBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Vue from 'vue'
import dayjs from 'dayjs'
import { mapActions } from 'vuex'
import condition from './condition'
import { userGroupRules } from '@/api/userGroup'

const dateRange = [
  { value: 'past', label: '昨日' },
  { value: 'thisWeek', label: '本周' },
  { value: 'thisMonth', label: '本月' },
  { value: 'lastWeek', label: '上周' },
  { value: 'lastMonth', label: '上月' },
  { value: 'past_7', label: '过去7天' },
  { value: 'past_30', label: '过去30天' },
  { value: 'past_90', label: '过去90天' },
  { value: 'static_time', label: '具体时间段' },
  { value: 'dynamic_time', label: '动态时间段' }
]

const converTimeKey = {
  YESTERDAY: { value: 'past' },
  THIS_WEEK: { value: 'thisWeek' },
  THIS_MONTH: { value: 'thisMonth' },
  LAST_WEEK: { value: 'lastWeek' },
  LAST_MONTH: { value: 'lastMonth' },
  NEARLY_SEVEN_DAYS: { value: 'past_7' },
  NEARLY_THIRTY_DAYS: { value: 'past_30' },
  NEARLY_NINETY_DAYS: { value: 'past_90' },
  STATIC: { value: 'static_time' },
  FIXED_START_TIME: { value: 'dynamic_time' }
}

export default {
  msg: '规则表单',
  data() {
    // 时间范围
    this.dateRange = dateRange

    return {
      firstLevel: {
        active: 'and',
        attribute: '100px',
        behavior: '100px'
      },

      secondAttrLevel: {
        active: 'and',
        attribute: '10px',
        behavior: '10px'
      },

      secondBehaviorLevel: {
        active: 'and',
        attribute: '10px',
        behavior: '10px'
      },

      // init data
      userAttrs: [],
      userBehaviors: [],

      // attribute
      attrList: [],
      attrCard: [],
      attrNum: 0,
      attrMaxinum: 10,

      // behavior
      behaviorList: [],
      behaviorCard: [],
      behaviorNum: 0,
      behaviorMaxinum: 5,

      // dialog
      dateDialog: {
        visible: false
      },

      // dateRangeForm
      dateRangeForm: {
        type: '', // start_time/dyncmaic_time
        layer: '', // outer/inner
        index: '', // index
        parent: '', // parent obj
        staticDate: '',
        dynamicDate: '',
        pastDays: ''
      },

      // validate rules
      dateRangeRules: {
        staticDate: [
          { required: true, message: '请选择日期范围', trigger: 'change' }
        ],
        dynamicDate: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
        pastDays: [{ required: true, message: '请输入天数', trigger: 'blur' }]
      }
    }
  },

  computed: {
    pageType() {
      // edit / add / preview
      return this.$route.query.pageType
    },

    is_preview() {
      return this.pageType === 'preview' ? true : false
    }
  },

  watch: {
    // update nums
    attrNum: {
      handler(newVal, oldVal) {
        this.updateRuleNums(newVal + this.behaviorNum)
      },
      deep: true
    },

    // update nums
    behaviorNum: {
      handler(newVal, oldVal) {
        this.updateRuleNums(newVal + this.attrNum)
      },
      deep: true
    }
  },

  created() {
    this.initRuleOptions()
  },

  mounted() {
    this.$on('submitValidate', () => {
      this.submitValidate()
    })

    this.$on('initRuleForm', (data) => {
      this.initRuleForm(data)
    })
  },

  methods: {
    // 用户属性 匹配规则发生了改变
    attributeRule(item) {
      if (item.valueEnd) {
        item.valueEnd = ''
      }
      // 如果匹配规则是  为空或者不为空
      if (item.rule && (item.rule === 'empty' || item.rule === 'unempty')) {
        item.element = Array(String(item.element))
      } else {
        item.element = String(item.element)
      }
      // 如果匹配规则是 包含或者不包含 （默认值修改）
      if (item.rule === 'include' || item.rule === 'uninclude') {
        item.attrVal = []
      } else if (item.rule === 'equal' || item.rule === 'unequal') {
        if (item.attrVal) {
          item.attrVal = ''
        }
      } else {
        item.attrVal = ''
      }

      if (item.element == 'Date' && item.rule == 'section') {
        item.attrVal = []
      }
    },
    ...mapActions('userGroup', ['updateRuleNums', 'updateRuleValidate']),

    // init rule form
    async initRuleForm(data) {
      await this.handleLoadOptions()
      const { operate, userBehavior, userProperties } = data

      this.firstLevel.active = operate.toLowerCase()
      this.secondAttrLevel.active = userProperties.operate.toLowerCase()
      this.secondBehaviorLevel.active = userBehavior.operate.toLowerCase()

      userProperties.rule.forEach((parent, parent_index) => {
        // add first attr
        if (!parent.rule) {
          let {
            index,
            condition,
            valueStart,
            valueEnd
          } = parent.ruleConfig.userProperties
          let userAttrs = this.userAttrs.find((ele) => ele.indexCode === index)
          let newObj = {
            index: parent_index,
            attr: index,
            rule: condition,
            ruleList: userAttrs.matchingRules,
            attrVal: valueStart,
            valList: userAttrs.value,
            element: userAttrs.indexDataType,
            valueEnd
          }
          if (
            newObj.element === 'Select' &&
            (newObj.rule === 'include' || newObj.rule === 'uninclude')
          ) {
            newObj.attrVal = valueStart.split(',')
          }
          if (condition == 'section' && valueEnd.indexOf('-') != -1) {
            newObj.attrVal = [valueStart, valueEnd]
          }
          this.attrList = this.attrList.concat(newObj)
          this.attrNum = this.attrNum + 1
          this.$nextTick(() => {
            const height1 = this.$refs['secondAttribute'].offsetHeight
            this.secondAttrLevel.attribute = (height1 - 80) / 2 + 'px'
            this.secondAttrLevel.behavior = (height1 - 80) / 2 + 'px'

            const height2 = this.$refs['attribute'].$el.offsetHeight
            this.firstLevel.attribute = height2 + 'px'
          })
        }

        if (parent.rule && parent.rule.length) {
          // add card list
          let attrLen = this.attrCard.length
          let attrIndex = attrLen > 0 ? this.attrCard[attrLen - 1].index + 1 : 0
          this.attrCard = this.attrCard.concat({ index: attrIndex, child: [] })

          // add second attr
          parent.rule.forEach((child, child_index) => {
            let {
              index,
              condition,
              valueStart,
              valueEnd
            } = child.ruleConfig.userProperties
            let userAttrs = this.userAttrs.find(
              (ele) => ele.indexCode === index
            )
            let newObj = {
              index: child_index,
              attr: index,
              rule: condition,
              ruleList: userAttrs.matchingRules,
              attrVal: valueStart,
              valList: userAttrs.value,
              element: userAttrs.indexDataType,
              valueEnd
            }
            if (
              newObj.element === 'Select' &&
              (newObj.rule === 'include' || newObj.rule === 'uninclude')
            ) {
              newObj.attrVal = valueStart.split(',')
            }
            if (condition == 'section' && valueEnd.indexOf('-') != -1) {
              newObj.attrVal = [valueStart, valueEnd]
            }

            this.attrCard[attrIndex].child = this.attrCard[
              attrIndex
            ].child.concat(newObj)
            this.attrCard[attrIndex].condition = {
              active: parent.operate.toLowerCase(),
              attribute: '10px',
              behavior: '10px'
            }
            this.attrNum = this.attrNum + 1
          })

          this.$nextTick(() => {
            const height = this.$refs['thirdAttribute' + attrIndex][0]
              .offsetHeight
            this.attrCard[attrIndex].condition.attribute =
              (height - 30) / 2 + 'px'
            this.attrCard[attrIndex].condition.behavior =
              (height - 30) / 2 + 'px'

            const height1 = this.$refs.secondAttribute.offsetHeight
            this.secondAttrLevel.attribute = (height1 - 80) / 2 + 'px'
            this.secondAttrLevel.behavior = (height1 - 80) / 2 + 'px'

            const height2 = this.$refs['attribute'].$el.offsetHeight
            this.firstLevel.attribute = height2 + 'px'
          })
        }
      })
      userBehavior.rule.forEach((parent, parent_index) => {
        // add first behavior
        if (!parent.rule) {
          let {
            index,
            condition,
            dimension,
            period,
            valueStart,
            valueEnd
          } = parent.ruleConfig.userBehavior

          let userBehav = this.userBehaviors.find(
            (ele) => ele.indexCode === index
          )

          // 标识、用户行为、时间范围、时间范围字典Key、【开始时间、结束时间（仅在isPeriod为“1”的情况下赋值）】、统计维度、维度列表、匹配规则、规则列表、行为数值、数值列表、标签类型、是否支持时间段筛选
          let newObj = {
            index: parent_index,
            behavior: index,
            timeRange: '',
            timeKey: '',
            startTime: '',
            endTime: '',
            dimension: dimension,
            dimensionList: userBehav.statisticalDimension,
            rule: condition,
            ruleList: userBehav.matchingRules,
            actionNum: valueStart,
            actionEndNum: valueEnd,
            valList: userBehav.value,
            element: userBehav.indexDataType,
            isPeriod: userBehav.ifPeriod,
            section: condition === 'section' ? true : false
          }
          if (
            newObj.element === 'Select' &&
            (newObj.rule === 'include' || newObj.rule === 'uninclude')
          ) {
            newObj.actionNum = valueStart.split(',')
          }
          if (condition == 'section' && valueEnd.indexOf('-') != -1) {
            newObj.actionNum = [valueStart, valueEnd]
          }
          // solve time range object
          const timeTypeList = [
            'THIS_WEEK',
            'THIS_MONTH',
            'LAST_WEEK',
            'LAST_MONTH',
            'YESTERDAY',
            'NEARLY_SEVEN_DAYS',
            'NEARLY_THIRTY_DAYS',
            'NEARLY_NINETY_DAYS'
          ]

          // static_time
          if (newObj.isPeriod === '1' && period.periodRule === 'STATIC') {
            newObj.startTime = dayjs(period.startTime).format('YYYY-MM-DD')
            newObj.endTime = dayjs(period.endTime).format('YYYY-MM-DD')
            newObj.timeRange = newObj.startTime + '-' + newObj.endTime
            newObj.timeKey = converTimeKey[period.periodRule].value
          }

          // dynamic_time
          if (
            newObj.isPeriod === '1' &&
            period.periodRule === 'FIXED_START_TIME'
          ) {
            newObj.startTime = dayjs(period.startTime).format('YYYY-MM-DD')
            newObj.endTime = period.endDay
            newObj.timeRange =
              newObj.startTime + '-' + '过去' + newObj.endTime + '天'
            newObj.timeKey = converTimeKey[period.periodRule].value
          }

          // other
          if (
            newObj.isPeriod === '1' &&
            timeTypeList.includes(period.periodRule)
          ) {
            newObj.timeKey = converTimeKey[period.periodRule].value
            newObj.timeRange = converTimeKey[period.periodRule].value
          }

          this.behaviorList = this.behaviorList.concat(newObj)
          this.behaviorNum = this.behaviorNum + 1

          this.$nextTick(() => {
            const height1 = this.$refs['secondBehavior'].offsetHeight
            this.secondBehaviorLevel.attribute = (height1 - 80) / 2 + 'px'
            this.secondBehaviorLevel.behavior = (height1 - 80) / 2 + 'px'

            const height2 = this.$refs['behavior'].$el.offsetHeight
            this.firstLevel.behavior = height2 + 'px'
          })
        }

        if (parent.rule && parent.rule.length) {
          // add card list
          let behavLen = this.behaviorCard.length
          let behavIndex =
            behavLen > 0 ? this.behaviorCard[behavLen - 1].index + 1 : 0
          this.behaviorCard = this.behaviorCard.concat({
            index: behavIndex,
            child: []
          })

          // add second attr
          parent.rule.forEach((child, child_index) => {
            let {
              index,
              condition,
              dimension,
              period,
              valueStart,
              valueEnd
            } = child.ruleConfig.userBehavior
            let userBehav = this.userBehaviors.find(
              (ele) => ele.indexCode === index
            )

            // 标识、用户行为、时间范围、时间范围字典Key、【开始时间、结束时间（仅在isPeriod为“1”的情况下赋值）】、统计维度、维度列表、匹配规则、规则列表、行为数值、数值列表、标签类型、是否支持时间段筛选
            let newObj = {
              index: child_index,
              behavior: index,
              timeRange: '',
              timeKey: '',
              startTime: '',
              endTime: '',
              dimension: dimension,
              dimensionList: userBehav.statisticalDimension,
              rule: condition,
              ruleList: userBehav.matchingRules,
              actionNum: valueStart,
              actionEndNum: valueEnd,
              valList: userBehav.value,
              element: userBehav.indexDataType,
              isPeriod: userBehav.ifPeriod,
              section: condition === 'section' ? true : false
            }
            if (
              newObj.element === 'Select' &&
              (newObj.rule === 'include' || newObj.rule === 'uninclude')
            ) {
              newObj.actionNum = valueStart.split(',')
            }
            if (condition == 'section' && valueEnd.indexOf('-') != -1) {
              newObj.actionNum = [valueStart, valueEnd]
            }

            // solve time range object
            const timeTypeList = [
              'THIS_WEEK',
              'THIS_MONTH',
              'LAST_WEEK',
              'LAST_MONTH',
              'YESTERDAY',
              'NEARLY_SEVEN_DAYS',
              'NEARLY_THIRTY_DAYS',
              'NEARLY_NINETY_DAYS'
            ]

            // static_time
            if (newObj.isPeriod === '1' && period.periodRule === 'STATIC') {
              newObj.startTime = dayjs(period.startTime).format('YYYY-MM-DD')
              newObj.endTime = dayjs(period.endTime).format('YYYY-MM-DD')
              newObj.timeRange = newObj.startTime + '-' + newObj.endTime
              newObj.timeKey = converTimeKey[period.periodRule].value
            }

            // dynamic_time
            if (
              newObj.isPeriod === '1' &&
              period.periodRule === 'FIXED_START_TIME'
            ) {
              newObj.startTime = dayjs(period.startTime).format('YYYY-MM-DD')
              newObj.endTime = period.endDay
              newObj.timeRange =
                newObj.startTime + '-' + '过去' + newObj.endTime + '天'
              newObj.timeKey = converTimeKey[period.periodRule].value
            }

            // other
            if (
              newObj.isPeriod === '1' &&
              timeTypeList.includes(period.periodRule)
            ) {
              newObj.timeKey = converTimeKey[period.periodRule].value
              newObj.timeRange = converTimeKey[period.periodRule].value
            }

            this.behaviorCard[behavIndex].child = this.behaviorCard[
              behavIndex
            ].child.concat(newObj)
            this.behaviorCard[behavIndex].condition = {
              active: parent.operate.toLowerCase(),
              attribute: '10px',
              behavior: '10px'
            }
            this.behaviorNum = this.behaviorNum + 1
          })

          this.$nextTick(() => {
            const height = this.$refs['thirdBehavior' + behavIndex][0]
              .offsetHeight
            this.behaviorCard[behavIndex].condition.attribute =
              (height - 30) / 2 + 'px'
            this.behaviorCard[behavIndex].condition.behavior =
              (height - 30) / 2 + 'px'

            const height1 = this.$refs.secondBehavior.offsetHeight
            this.secondBehaviorLevel.attribute = (height1 - 80) / 2 + 'px'
            this.secondBehaviorLevel.behavior = (height1 - 80) / 2 + 'px'

            const height2 = this.$refs['behavior'].$el.offsetHeight
            this.firstLevel.behavior = height2 + 'px'
          })
        }
      })
    },

    // init rule options
    async initRuleOptions() {
      // get attibute rules
      await userGroupRules({ type: 'userProperties' }, (res) => {
        this.userAttrs = res
      })
      // get behavior rules
      await userGroupRules({ type: 'userBehavior' }, (res) => {
        this.userBehaviors = res
      })
    },

    // async load options
    handleLoadOptions() {
      return new Promise((resolve, reject) => {
        userGroupRules({ type: 'userProperties' }, (res) => {
          this.userAttrs = res
          userGroupRules({ type: 'userBehavior' }, (res) => {
            this.userBehaviors = res
            resolve()
          })
        })
      })
    },

    // validate
    submitValidate() {
      let pass = true

      // attr validate
      this.attrList.forEach((ele, index) => {
        this.$refs[`attrValidateForm${index}`][0].validate((valid) => {
          if (!valid) {
            pass = false
          }
        })
      })

      // attr child validate
      this.attrCard.forEach((ele, p) => {
        ele.child.forEach((ele2, c) => {
          this.$refs[`attrValidateForm${p}${c}`][0].validate((valid) => {
            if (!valid) {
              pass = false
            }
          })
        })
      })

      // behavior validate
      this.behaviorList.forEach((ele, index) => {
        this.$refs[`behaviorValidateForm${index}`][0].validate((valid) => {
          if (!valid) {
            pass = false
          }
        })
      })

      // behavior child validate
      this.behaviorCard.forEach((ele, p) => {
        ele.child.forEach((ele2, c) => {
          this.$refs[`behaviorValidateForm${p}${c}`][0].validate((valid) => {
            if (!valid) {
              pass = false
            }
          })
        })
      })

      this.updateRuleValidate(pass)
    },

    // add Attributes
    handleAddAttrs(command) {
      // Maximum of 10
      if (this.attrNum + 1 > this.attrMaxinum) {
        this.$message.info('限制用户属性最多十条')
        return
      }

      if (command === 'a') {
        const arr = this.attrList.length
        const index = arr > 0 ? this.attrList[arr - 1].index + 1 : 0

        this.attrList = this.attrList.concat({
          // 标识、属性、匹配规则、匹配列表、属性值、属性列表、标签类型
          index: index,
          attr: '',
          rule: '',
          ruleList: [],
          attrVal: [],
          valList: [],
          element: '',
          valueEnd: ''
        })

        this.attrNum = this.attrNum + 1

        const height1 = this.$refs['secondAttribute'].offsetHeight
        this.secondAttrLevel.attribute = (height1 - 30) / 2 + 'px'
        this.secondAttrLevel.behavior = (height1 - 30) / 2 + 'px'

        const height2 = this.$refs['attribute'].$el.offsetHeight
        this.firstLevel.attribute = height2 + 60 + 'px'
      }

      if (command === 'b') {
        const arr = this.attrCard.length
        const index = arr > 0 ? this.attrCard[arr - 1].index + 1 : 0
        this.attrCard = this.attrCard.concat({ index: index, child: [] })

        const height1 = this.$refs.secondAttribute.offsetHeight
        this.secondAttrLevel.attribute = (height1 + 60) / 2 + 'px'
        this.secondAttrLevel.behavior = (height1 + 60) / 2 + 'px'

        const height2 = this.$refs['attribute'].$el.offsetHeight
        this.firstLevel.attribute = height2 + 120 + 'px'
      }
    },

    // add Behavior
    handleAddBehavior(command) {
      // Maximum of 5
      if (this.behaviorNum + 1 > this.behaviorMaxinum) {
        this.$message.info('限制用户行为最多五条')
        return
      }

      if (command === 'a') {
        const arr = this.behaviorList.length
        const index = arr > 0 ? this.behaviorList[arr - 1].index + 1 : 0

        this.behaviorList = this.behaviorList.concat({
          // 标识、用户行为、时间范围、时间范围字典Key、是否支持时间段筛选、【开始时间、结束时间（仅在isPeriod为“1”的情况下赋值）】、统计维度、维度列表、匹配规则、规则列表、行为数值、行为区间数值、数值列表、标签类型、显示区间值
          index: index,
          behavior: '',
          timeRange: '',
          timeKey: '',
          isPeriod: '',
          startTime: '',
          endTime: '',
          dimension: '',
          dimensionList: [],
          rule: '',
          ruleList: [],
          actionNum: [],
          actionEndNum: '',
          valList: [],
          element: '',
          section: false
        })

        this.behaviorNum = this.behaviorNum + 1

        const height1 = this.$refs['secondBehavior'].offsetHeight
        this.secondBehaviorLevel.attribute = (height1 - 30) / 2 + 'px'
        this.secondBehaviorLevel.behavior = (height1 - 30) / 2 + 'px'

        const height2 = this.$refs['behavior'].$el.offsetHeight
        this.firstLevel.behavior = height2 + 60 + 'px'
      }

      if (command === 'b') {
        const arr = this.behaviorCard.length
        const index = arr > 0 ? this.behaviorCard[arr - 1].index + 1 : 0
        this.behaviorCard = this.behaviorCard.concat({
          index: index,
          child: []
        })

        const height1 = this.$refs.secondBehavior.offsetHeight
        this.secondBehaviorLevel.attribute = (height1 + 60) / 2 + 'px'
        this.secondBehaviorLevel.behavior = (height1 + 60) / 2 + 'px'

        const height2 = this.$refs['behavior'].$el.offsetHeight
        this.firstLevel.behavior = height2 + 120 + 'px'
      }
    },

    // add Third Attribute
    handleAddThirdAttribute(cur) {
      // Maximum of 10
      if (this.attrNum + 1 > this.attrMaxinum) {
        this.$message.info('限制用户属性最多十条')
        return
      }

      const arr = this.attrCard[cur.index].child.length
      const index =
        arr > 0 ? this.attrCard[cur.index].child[arr - 1].index + 1 : 0

      this.attrCard[cur.index].child = this.attrCard[cur.index].child.concat({
        index: index,
        attr: '',
        rule: '',
        ruleList: [],
        attrVal: [],
        valList: [],
        element: '',
        valueEnd: ''
      })

      this.attrCard[cur.index].condition = {
        active: 'and',
        attribute: '10px',
        behavior: '10px'
      }
      this.attrNum = this.attrNum + 1

      const height = this.$refs['thirdAttribute' + cur.index][0].offsetHeight
      this.attrCard[cur.index].condition.attribute = (height - 30) / 2 + 'px'
      this.attrCard[cur.index].condition.behavior = (height - 30) / 2 + 'px'

      const height1 = this.$refs.secondAttribute.offsetHeight
      this.secondAttrLevel.attribute = (height1 - 30) / 2 + 'px'
      this.secondAttrLevel.behavior = (height1 - 30) / 2 + 'px'

      const height2 = this.$refs['attribute'].$el.offsetHeight
      this.firstLevel.attribute = height2 + 60 + 'px'
    },

    // add Third Behavior
    handleAddThirdBehavior(cur) {
      // Maximum of 5
      if (this.behaviorNum + 1 > this.behaviorMaxinum) {
        this.$message.info('限制用户行为最多五条')
        return
      }

      const arr = this.behaviorCard[cur.index].child.length
      const index =
        arr > 0 ? this.behaviorCard[cur.index].child[arr - 1].index + 1 : 0
      this.behaviorCard[cur.index].child = this.behaviorCard[
        cur.index
      ].child.concat({
        index: index,
        behavior: '',
        timeRange: '',
        timeKey: '',
        isPeriod: '',
        startTime: '',
        endTime: '',
        dimension: '',
        dimensionList: [],
        rule: '',
        ruleList: [],
        actionNum: [],
        actionEndNum: '',
        valList: [],
        element: '',
        section: false
      })

      this.behaviorCard[cur.index].condition = {
        active: 'and',
        attribute: '10px',
        behavior: '10px'
      }
      this.behaviorNum = this.behaviorNum + 1

      const height = this.$refs['thirdBehavior' + cur.index][0].offsetHeight
      this.behaviorCard[cur.index].condition.attribute =
        (height - 30) / 2 + 'px'
      this.behaviorCard[cur.index].condition.behavior = (height - 30) / 2 + 'px'

      const height1 = this.$refs.secondBehavior.offsetHeight
      this.secondBehaviorLevel.attribute = (height1 - 30) / 2 + 'px'
      this.secondBehaviorLevel.behavior = (height1 - 30) / 2 + 'px'

      const height2 = this.$refs['behavior'].$el.offsetHeight
      this.firstLevel.behavior = height2 + 60 + 'px'
    },

    // Del Attribute Items
    handleDelAttr(cur) {
      this.attrList.splice(cur, 1)
      this.attrNum = this.attrNum - 1

      const height1 = this.$refs['secondAttribute'].offsetHeight
      this.secondAttrLevel.attribute = (height1 - 150) / 2 + 'px'
      this.secondAttrLevel.behavior = (height1 - 150) / 2 + 'px'

      const height2 = this.$refs['attribute'].$el.offsetHeight
      this.firstLevel.attribute = height2 - 60 + 'px'
    },

    // Del Third Attribute Items
    handleDelThirdAttr(cur, index) {
      this.attrCard[cur.index].child.splice(index, 1)
      this.attrNum = this.attrNum - 1

      const height = this.$refs['thirdAttribute' + cur.index][0].offsetHeight
      const active = this.attrCard[cur.index].condition.active
      const result = (height - 150) / 2 + 'px'

      Vue.set(this.attrCard, cur.index, {
        child: this.attrCard[cur.index].child,
        condition: { attribute: result, behavior: result, active: active },
        index: cur.index
      })

      const height1 = this.$refs.secondAttribute.offsetHeight
      this.secondAttrLevel.attribute = (height1 - 150) / 2 + 'px'
      this.secondAttrLevel.behavior = (height1 - 150) / 2 + 'px'

      const height2 = this.$refs['attribute'].$el.offsetHeight
      this.firstLevel.attribute = height2 - 60 + 'px'
    },

    // Del Behavior Items
    handleDelBehavior(cur) {
      this.behaviorList.splice(cur, 1)
      this.behaviorNum = this.behaviorNum - 1

      const height1 = this.$refs['secondBehavior'].offsetHeight
      this.secondBehaviorLevel.attribute = (height1 - 150) / 2 + 'px'
      this.secondBehaviorLevel.behavior = (height1 - 150) / 2 + 'px'

      const height2 = this.$refs['behavior'].$el.offsetHeight
      this.firstLevel.behavior = height2 - 60 + 'px'
    },

    // Del Third Behavior Items
    handleDelThirdBehavior(cur, index) {
      this.behaviorCard[cur.index].child.splice(index, 1)
      this.behaviorNum = this.behaviorNum - 1

      const height = this.$refs['thirdBehavior' + cur.index][0].offsetHeight
      const active = this.behaviorCard[cur.index].condition.active
      const result = (height - 150) / 2 + 'px'

      Vue.set(this.behaviorCard, cur.index, {
        child: this.behaviorCard[cur.index].child,
        condition: { attribute: result, behavior: result, active: active },
        index: cur.index
      })

      const height1 = this.$refs.secondBehavior.offsetHeight
      this.secondBehaviorLevel.attribute = (height1 - 150) / 2 + 'px'
      this.secondBehaviorLevel.behavior = (height1 - 150) / 2 + 'px'

      const height2 = this.$refs['behavior'].$el.offsetHeight
      this.firstLevel.behavior = height2 - 60 + 'px'
    },

    // solve attr change event
    handleAttrRuleChange(cur, index) {
      if (!cur.attr) {
        cur.element = ''
        cur.rule = ''
        cur.ruleList = []
        return
      }
      const rules = this.userAttrs.find((ele) => ele.indexCode === cur.attr)
      // clear data
      this.attrList[index].attrVal = []
      this.attrList[index].rule = ''
      // 用户组 属性列表
      let attrList = [
        'formal_course_open_time',
        'zhanchi_first_pay_time',
        'first_login_time'
      ]
      // attrList 包含当前的 属性名称
      if (
        (!cur.element || cur.element == 'Date') &&
        attrList.includes(cur.attr)
      ) {
        this.attrList[index].attrVal = ''
      }
      // fill data
      this.attrList[index].valList = rules.value
      this.attrList[index].ruleList = rules.matchingRules
      this.attrList[index].element = rules.indexDataType
    },

    // solve third attr change event
    handleThirdAttrRuleChange(parent, child, index) {
      if (!child.attr) {
        child.element = ''
        child.rule = ''
        child.ruleList = []
        return
      }
      const rules = this.userAttrs.find((ele) => ele.indexCode === child.attr)

      // clear data
      this.attrCard[parent.index].child[index].attrVal = []
      this.attrCard[parent.index].child[index].rule = ''
      // 用户组 属性列表
      let attrList = [
        'formal_course_open_time',
        'zhanchi_first_pay_time',
        'first_login_time'
      ]
      // attrList 包含当前的 属性名称
      if (
        (!child.element || child.element == 'Date') &&
        attrList.includes(child.attr)
      ) {
        this.attrCard[parent.index].child[index].attrVal = ''
      }
      // fill data
      this.attrCard[parent.index].child[index].valList = rules.value
      this.attrCard[parent.index].child[index].ruleList = rules.matchingRules
      this.attrCard[parent.index].child[index].element = rules.indexDataType
    },

    // solve behavior change event
    handleBehaviorRuleChange(cur, index) {
      if (!cur.behavior) {
        cur.element = ''
        cur.rule = ''
        this.behaviorList[index].actionNum = ''
        this.behaviorList[index].dimension = ''
        this.behaviorList[index].timeKey = ''
        this.behaviorList[index].timeRange = ''
        this.behaviorList[index].isPeriod = ''
        this.behaviorList[index].dimensionList = []
        this.behaviorList[index].ruleList = []
        return
      }
      const rules = this.userBehaviors.find(
        (ele) => ele.indexCode === cur.behavior
      )
      // clear data
      this.behaviorList[index].rule = ''
      this.behaviorList[index].actionNum =
        rules.indexDataType === 'Select' ? [] : ''
      this.behaviorList[index].dimension = ''
      this.behaviorList[index].timeRange = ''
      this.behaviorList[index].actionEndNum = ''
      this.behaviorList[index].section = false

      // fill data
      this.behaviorList[index].valList = rules.value
      this.behaviorList[index].isPeriod = rules.ifPeriod
      this.behaviorList[index].ruleList = rules.matchingRules
      this.behaviorList[index].element = rules.indexDataType
      this.behaviorList[index].dimensionList = rules.statisticalDimension
      
    },

    // solve third behavior change event
    handleThirdBehaviorRuleChange(parent, child, index) {
      if (!child.behavior) {
        child.element = ''
        child.rule = ''
        this.behaviorCard[parent.index].child[index].dimension = ''
        this.behaviorCard[parent.index].child[index].timeKey = ''
        this.behaviorCard[parent.index].child[index].timeRange = ''
        this.behaviorCard[parent.index].child[index].isPeriod = ''
        this.behaviorCard[parent.index].child[index].dimensionList = []
        this.behaviorCard[parent.index].child[index].ruleList = []
        return
      }
      const rules = this.userBehaviors.find(
        (ele) => ele.indexCode === child.behavior
      )

      // clear data
      this.behaviorCard[parent.index].child[index].rule = ''
      this.behaviorCard[parent.index].child[index].actionNum =
        rules.indexDataType === 'Select' ? [] : ''
      this.behaviorCard[parent.index].child[index].dimension = ''
      this.behaviorCard[parent.index].child[index].timeRange = ''
      this.behaviorCard[parent.index].child[index].actionEndNum = ''
      this.behaviorCard[parent.index].child[index].section = false

      // fill data
      this.behaviorCard[parent.index].child[index].valList = rules.value
      this.behaviorCard[parent.index].child[index].isPeriod = rules.ifPeriod
      this.behaviorCard[parent.index].child[index].ruleList =
        rules.matchingRules
      this.behaviorCard[parent.index].child[index].element = rules.indexDataType
      this.behaviorCard[parent.index].child[index].dimensionList =
        rules.statisticalDimension
    },

    // solve date range
    handleTimeRangeChange(index, cur) {
      // before clear data which add timeKey
      this.behaviorList[index].timeKey = cur.timeRange

      const range = ['static_time', 'dynamic_time']
      if (range.includes(cur.timeRange)) {
        // position and fill
        this.dateDialog.visible = true
        this.dateRangeForm.layer = 'outer'
        this.dateRangeForm.index = index
        this.dateRangeForm.type = cur.timeRange

        // clear
        this.dateRangeForm.staticDate = ''
        this.dateRangeForm.dynamicDate = ''
        this.dateRangeForm.pastDays = ''
        this.behaviorList[index].timeRange = ''
      }
    },

    // solve third date range
    handleThirdTimeRangeChange(parent, child, index) {
      // before clear data which add timeKey
      this.behaviorCard[parent.index].child[index].timeKey = child.timeRange

      const range = ['static_time', 'dynamic_time']
      if (range.includes(child.timeRange)) {
        // position and fill
        this.dateDialog.visible = true
        this.dateRangeForm.layer = 'inner'
        this.dateRangeForm.index = index
        this.dateRangeForm.parent = parent
        this.dateRangeForm.type = child.timeRange

        // clear
        this.dateRangeForm.staticDate = ''
        this.dateRangeForm.dynamicDate = ''
        this.dateRangeForm.pastDays = ''
        this.behaviorCard[parent.index].child[index].timeRange = ''
      }
    },

    // solve date dialog close
    handleDateDialogClose() {
      this.$refs['dateForm'].resetFields()
    },

    // fill behaivor date
    handleDateFormBtn() {
      this.$refs['dateForm'].validate((valid) => {
        if (valid) {
          const {
            layer,
            index,
            parent,
            type,
            staticDate,
            dynamicDate,
            pastDays
          } = this.dateRangeForm

          if (layer === 'outer' && type === 'static_time') {
            this.behaviorList[index].startTime = staticDate[0]
            this.behaviorList[index].endTime = staticDate[1]
            this.behaviorList[index].timeRange =
              staticDate[0] + '-' + staticDate[1]
          }

          if (layer === 'outer' && type === 'dynamic_time') {
            this.behaviorList[index].startTime = dynamicDate
            this.behaviorList[index].endTime = pastDays
            this.behaviorList[index].timeRange =
              dynamicDate + '-' + '过去' + pastDays + '天'
          }

          if (layer === 'inner' && type === 'static_time') {
            this.behaviorCard[parent.index].child[index].startTime =
              staticDate[0]
            this.behaviorCard[parent.index].child[index].endTime = staticDate[1]
            this.behaviorCard[parent.index].child[index].timeRange =
              staticDate[0] + '-' + staticDate[1]
          }

          if (layer === 'inner' && type === 'dynamic_time') {
            this.behaviorCard[parent.index].child[index].startTime = dynamicDate
            this.behaviorCard[parent.index].child[index].endTime = pastDays
            this.behaviorCard[parent.index].child[index].timeRange =
              dynamicDate + '-' + '过去' + pastDays + '天'
          }

          this.dateDialog.visible = false
        }
      })
    },

    // solve Behavior Rule Section
    handleBehaviorRuleSection(index, cur) {
      if (cur.actionEndNum) {
        cur.actionEndNum = ''
      }
      // 当规则选择了 为空 / 不为空   隐藏选择值
      if (
        cur.rule &&
        (cur.rule === 'empty' || cur.rule === 'unempty') &&
        (cur.behavior === 'sys_source_zh' || cur.behavior === 'sys_source_last')
      ) {
        cur.element = Array(String(cur.element))
      } else {
        cur.element = String(cur.element)
      }
      // 当规则为 包含不包含  选项值多选
      if (
        (cur.rule === 'include' || cur.rule === 'uninclude') &&
        (cur.behavior === 'sys_source_zh' || cur.behavior === 'sys_source_last')
      ) {
        cur.actionNum = []
      } else if (
        (cur.rule === 'equal' || cur.rule === 'unequal') &&
        (cur.behavior === 'sys_source_zh' || cur.behavior === 'sys_source_last')
      ) {
        if (cur.actionNum) {
          cur.actionNum = ''
        }
      } else {
        cur.actionNum = ''
      }
      this.behaviorList[index].section = cur.rule == 'section' ? true : false
    },

    // solve Third Behavior Rule Section
    handleThirdBehaviorRuleSection(parent, child, index) {
      if (child.actionEndNum) {
        child.actionEndNum = ''
      }
      // 当规则选择了 为空 / 不为空   隐藏选择值
      if (
        child.rule &&
        (child.rule === 'empty' || child.rule === 'unempty') &&
        (child.behavior === 'sys_source_zh' ||
          child.behavior === 'sys_source_last')
      ) {
        child.element = Array(String(child.element))
      } else {
        child.element = String(child.element)
      }
      // 当规则为 包含不包含  选项值多选
      if (
        (child.rule === 'include' || child.rule === 'uninclude') &&
        (child.behavior === 'sys_source_zh' ||
          child.behavior === 'sys_source_last')
      ) {
        child.actionNum = []
      } else if (
        (child.rule === 'equal' || child.rule === 'unequal') &&
        (child.behavior === 'sys_source_zh' ||
          child.behavior === 'sys_source_last')
      ) {
        if (child.actionNum) {
          child.actionNum = ''
        }
      } else {
        child.actionNum = ''
      }
      this.behaviorCard[parent.index].child[index].section =
        child.rule === 'section' ? true : false
    },

    // solve FirstLevel
    handleFirstLevel(e) {
      this.firstLevel.active = e.target.dataset.condition
    },

    // solve Second Attr Level
    handleSecondAttrLevel(e) {
      this.secondAttrLevel.active = e.target.dataset.condition
    },

    // Solve second behavior level
    handleSecondBehaviorLevel(e) {
      this.secondBehaviorLevel.active = e.target.dataset.condition
    },

    // Solve third attribute level
    handleThirdAttributeLevel(e, cur) {
      Vue.set(this.attrCard, cur.index, {
        child: this.attrCard[cur.index].child,
        condition: { active: e.target.dataset.condition },
        index: cur.index
      })
    },

    // Solve third behavior level
    handleThirdBehaviorLevel(e, cur) {
      Vue.set(this.behaviorCard, cur.index, {
        child: this.behaviorCard[cur.index].child,
        condition: { active: e.target.dataset.condition },
        index: cur.index
      })
    },

    // 只能保留正整数
    reservedInteger(e) {
      if (!new RegExp(/^[0-9]*$/).test(e.target.value)) {
        this.dateRangeForm.pastDays = ''
      }
    }
  },

  components: {
    condition
  }
}
</script>

<style lang="less" scoped>
.first-level-wrap,
.second-level-wrap,
.third-level-wrap {
  width: 100%;
  display: flex;
}

.first-level-from-box {
  margin-left: 50px;
  margin-top: 20px;
}

.second-level-form-box,
.third-level-form-box {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  margin-left: 30px;
  margin-top: 10px;
}

.attribute-card {
  min-width: 800px;
}

.action-card {
  min-width: 1000px;
}

.action-child-card,
.attribute-child-card {
  min-width: 800px;
  margin-left: 0;
  margin-top: 15px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}

.clearfix:after {
  clear: both;
}

.custom-dialog {
  & .dialog-body {
    padding: 20px;
  }

  & .tips {
    width: 100%;
    color: #f89a9a;
  }
}

:deep(.el-button.is-circle) {
  padding: 10px 10px !important;
}

:deep(.el-divider--horizontal) {
  width: 98%;
  margin-left: 10px;
}

:deep(.el-date-editor .el-range-separator) {
  padding: 0;
}

:deep(.el-input input::-webkit-outer-spin-button),
:deep(.el-input input::-webkit-inner-spin-button) {
  -webkit-appearance: none !important;
}
:deep(.el-input input[type='number']) {
  -moz-appearance: textfield;
}
:deep(.el-input .el-input__inner) {
  line-height: 1px !important;
}
</style>
